<template>
    <div class="detailglobal">
        <div>
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/forum/' + obj.pBoardId }">{{ obj.pBoardName }}</el-breadcrumb-item>
                <el-breadcrumb-item>
                    <a :href="'/forum/' + obj.pBoardId + '/' + obj.boardId">{{ obj.boardName }}</a>
                </el-breadcrumb-item>
                <el-breadcrumb-item>{{ obj.title }}</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="content">

            <div class="title">{{ obj.title }}<el-button v-if="userId == obj.userId" type="primry"
                    @click="edit">编辑</el-button></div>
            <div class="personal">

                <div class="avatar" style="margin-right: 10px;"><img src="../assets/default.png"
                        v-if="obj.avatar == null" style="width: 50px;height: 50px;" alt=""></div>
                <div>
                    <div style="    color: #4e5969;">{{ obj.nickName }}</div>
                    <div style="    color: #4e5969;">{{ obj.postTime }}{{ obj.userIpAddress }} 观看{{ obj.readCount }}
                    </div>
                    <div style="    color: #4e5969;"><el-icon :size="20" @click="star(obj.articleId)">
                                    <Star style="color: rgb(121.3,187.1,255);" v-if=" haveLike== true" />
                                    <Star v-else />
                                </el-icon>{{obj.goodCount}}</div>
                </div>
            </div>
            <div id="detail" v-html="obj.content">

            </div>
            <el-image-viewer v-if="showViewer" ref="imageViewerRef" :initial-index="previewImgIndex"
                @close="closeViewer" :url-list="previewImgList" />
            <!-- <ImageViewer ref="imageViewerRef" :imageList="previewImgList"></ImageViewer> -->
        </div>
        <div class="fjlist">
            <div v-for="(item, index) in fjlist" :key="index" style="margin-right: 10px;">{{ item.fileName }} <el-button
                    type="primary" @click="download(item)">下载</el-button>
            </div>
        </div>
        <div class="comment">
            <div class="titlecomment">评论</div>
            <div class="postcomment">
                <div style="width: 90%;">
                    <el-input type="textarea" v-model="formData.content" placeholder="请输入" />
                    <div style="display: flex;">
                        <el-upload name="file" :show-file-list="false"
                            accept=".png,.PNG,.jpg,.JpG,.jpeg,.JPEG,gif,.GIF,.bmp,.BMP" :multiple="false"
                            :http-request="selectImg">
                            <span class="iconfont icon-image"></span>

                        </el-upload>
                        <div v-if="commentImage != null" style="position: relative;">
                            <el-icon :size="20" style="position: absolute;top: 0px; right: 0px;" @click="qingchu()">
                                <Close />
                            </el-icon>
                            <img :src="commentImage" style="width: 100px;height: 100px;" alt="">
                        </div>
                    </div>
                </div>
                <div>
                    <el-button type="primary" @click="fabiao()">发表</el-button>
                </div>
            </div>
            <div class="commentylist" :key="index" v-for="(item, index) in commentlist" style="margin-bottom:10px;">
                <div style="display:flex;margin-bottom:10px;">
                    <div class="avatar" style="width: 50px;height: 50px;border-radius: 50%;margin-right: 10px;">
                        <img src="../assets/default.png" v-if="item.avatar == null" style="width: 50px;height: 50px;"
                            alt="">
                        <img v-else :src="item.avatar" style="width: 50px;height: 50px;border-radius: 50%;" alt="">
                    </div>
                    <div class="user">
                        <div class="username" style="margin-bottom: 10px;">{{ item.nickName }}{{ item.createBy }}{{
                            item.postTime }}</div>
                        <div class="username" v-html="item.content" style="margin-bottom:10px;"></div>
                        <div class="username" v-if="item.imgPath !== null">
                            <img :src="'/api/file/getImage/' + item.imgPath" style="width: 50px;height: 50px;" alt="">
                        </div>
                        <div style="display:flex;">

                            <div class="username"
                                style="color: rgb(102, 102, 102);font-size: 14px; margin-right:10px;cursor: pointer;"
                                @click="pl1(item)"><i class="el-icon-edit"></i> 回复</div>

                            <div class="username"
                                style="color: rgb(102, 102, 102);font-size: 14px; margin-right:10px;cursor: pointer;"
                                @click="dz(item.commentId)"> <el-icon :size="20">
                                    <Star style="color: rgb(121.3,187.1,255);" v-if="item.likeType == 1" />
                                    <Star v-else />
                                </el-icon> <span v-if="item.goodCount !== 0"> {{ item.goodCount }}</span> <span
                                    v-if="item.goodCount == 0">点赞</span></div>
                        </div>
                    </div>
                </div>
                <div class="commentylist" style="padding-left:100px;margin-bottom:10px;box-sizing:border-box;"
                    v-for="(itemm, index) in item.children" :key="index">
                    <div style="display:flex">
                        <div class="avatar" style="width: 50px;height: 50px;border-radius: 50%;margin-right: 10px;">
                            <img src="../assets/default.png" v-if="itemm.avatar == null"
                                style="width: 50px;height: 50px;" alt="">
                            <img v-else :src="itemm.avatar" style="width: 50px;height: 50px;border-radius: 50%;" alt="">
                        </div>
                        <div class="user">
                            <div class="username" style="margin-bottom: 10px;">
                                {{ itemm.nickName }}回复{{ itemm.replyNickName }}{{ itemm.createBy }}{{ item.postTime }}
                            </div>
                            <div class="username" v-html="itemm.content"></div>
                            <div class="username" v-if="itemm.imgPath !== null">
                                <img :src="'/api/file/getImage/' + itemm.imgPath" style="width: 50px;height: 50px;"
                                    alt="">
                            </div>
                            <div style="display:flex;">

                                <div class="username"
                                    style="color: rgb(102, 102, 102);font-size: 14px; margin-right:10px;cursor: pointer;"
                                    @click="pl2(itemm, item)"><i class="el-icon-edit"></i> 回复</div>

                                <div class="username" style="color: rgb(102, 102, 102);font-size: 14px;cursor: pointer;"
                                    @click="dz(itemm.commentId)"><i class="el-icon-delete"></i> <el-icon :size="20">
                                        <Star style="color: rgb(121.3,187.1,255);" v-if="itemm.likeType == 1" />
                                        <Star v-else />

                                    </el-icon> <span v-if="itemm.goodCount !== 0"> {{ itemm.goodCount }}</span> <span
                                        v-if="itemm.goodCount == 0">点赞</span></div>

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="mulu">
            <div class="mulu-contain">
                <div class="mulutitle">目录</div>
                <div v-for="item in tocarray" @click="clicktac(item)" :style="{ 'padding-left': item.level * 15 + 'px' }" :class="item.id ==curid ? 'active':''" class="tocitem">
                    {{ item.title }}
                </div>
            </div>
        </div>
        <el-dialog title="回复" :append-to-body="true" :close-on-click-modal="false" :close-on-press-escape="false"
            width="500" :before-close="handleClose3" :model-value="getemailvisible1">
            <el-form :model="formData" label-width="auto" ref="getemailform" :rules="rules1" style="max-width: 600px">
                <el-form-item>
                    <el-input v-model="formData.content" type="textarea" style="width: 100%;" />

                </el-form-item>
                <el-form-item>
                    <el-upload name="file" :show-file-list="false"
                        accept=".png,.PNG,.jpg,.JpG,.jpeg,.JPEG,gif,.GIF,.bmp,.BMP" :multiple="false"
                        :http-request="selectImg">
                        <span class="iconfont icon-image"></span>

                    </el-upload>
                    <div v-if="commentImage != null" style="position: relative;">
                        <el-icon :size="20" style="position: absolute;top: 0px; right: 0px;" @click="qingchu()">
                            <Close />
                        </el-icon>
                        <img :src="commentImage" style="width: 100px;height: 100px;" alt="">
                    </div>
                </el-form-item>
                <el-button type="primary" @click="fabiao()" style="width: 100%;">
                    确认
                </el-button>
            </el-form>
        </el-dialog>
    </div>
</template>
<script setup>
import { getCurrentInstance, nextTick, onMounted, onUnmounted, ref } from 'vue';
import service from '../utils/request';
import { useStore } from "vuex";
import router from '../router';
import { useRoute } from 'vue-router';
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-light.css' //样式
import { ElMessage, ElMessageBox } from 'element-plus';

const store = useStore();
const haveLike=ref(true)
onMounted(() => {
// window.addEventListener("scroll",listionerscroller,false);
// window.addEventListener("resize",listenresize,false)    
getdetail()
    getcomment()

})
onUnmounted(() => {
    // window.removeEventListener('scroll', listionerscroller, false)
    
    
  })
  const star=async(item)=>{
const res=await  service.get("/forum/doLike",{
params:{
    articleId:item
}
})
if(res.code == 1){
    // getdetail()
    haveLike.value = !haveLike.value
    if( haveLike.value == true){
        obj.value.goodCount+=1
    }else{
        obj.value.goodCount-=1
        
    }
}
  }
const initScroll = () => {
  let scroll = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
  return scroll
}
const listionerscroller=()=>{
    let currentScrollTop=initScroll();
    tocarray.value.some((item,index)=>{
        if( (index < tocarray.value.length - 1 &&
          currentScrollTop >= tocarray.value[index].offsetTop &&
          currentScrollTop < tocarray.value[index + 1].offsetTop) ||
        (index == tocarray.value.length - 1 &&
          currentScrollTop < tocarray.value[index].offsetTop)){
            curid.value=item.id
            return true
          }
    })
}
const listenresize=()=>{

}
const edit = () => {
    router.push({
        path: "/add",
        query: {
            id: obj.value.articleId
        }
    })

}
const curid=ref(null);
const tocarray = ref([]);
const getemailvisible1 = ref(false)
const mululist = ref([]);
const { proxy } = getCurrentInstance();
const commentlist = ref([]);
const showViewer = ref(null)
const content = ref("");
const previewImgIndex = ref(null);
const obj = ref({});
const route = useRoute();
const commentImage = ref(null);
const previewImgList = ref([]);
const ImageViewerref = ref(null);
const fjlist = ref([])
const pCommentId = ref(0);
const replyUserId = ref("");
const image = ref(null);
const formData = ref({});
const userId = ref("");
const clicktac=(item)=>{
    curid.value=item.id
    const dom=document.querySelector("#"+item.id);
    dom.scrollIntoView({
        behavior:"smooth",
        block:"start"
    })

}
const qingchu = () => {
    image.value = null;
    commentImage.value = null
}
const pl1 = (item) => {
    console.log(item)
    replyUserId.value = item.userId
    pCommentId.value = item.commentId
    getemailvisible1.value = true
}
const pl2 = (item) => {
    console.log(item)
    replyUserId.value = item.userId
    pCommentId.value = item.pCommentId
    getemailvisible1.value = true
}
const dz = async (cid) => {
    const res = await service.get("/comment/dolike", {
        params: {
            commentId: cid
        }
    })
    console.log(res)
    if (res.code == 0) {
        ElMessage({
            message: "未登录",
            type: "warning"
        })
    } else {
        getcomment()
    }

}
const selectImg = (file) => {
    console.log(file)
    file = file.file;
    let img = new FileReader();

    img.readAsDataURL(file);
    console.log(file)

    img.onload = ({ target }) => {
        let imgData = target.result;
        commentImage.value = imgData;
        formData.value.image = file;
    };

}
const handleClose3 = () => {
    getemailvisible1.value = false
}
const fabiao = async () => {
    if (formData.value.content == '') {
        ElMessage({
            message: "内容不能为空",
            type: "warning"
        })
        return
    }
    let res = await proxy.Request({
        url: "/comment/postcomment",
        params: {
            articleId: route.params.boardId,
            pCommentId: pCommentId.value,
            content: formData.value.content,
            image: formData.value.image,
            replyUserId: replyUserId.value

        }
    });
    // const res = await service.post("/comment/postcomment", {
    //     // params:{
    //         articleId: route.params.boardId,
    //         pCommentId: pCommentId.value,
    //         content: formData.value.content,
    //         image: formData.value.image,
    //         replyUserId: replyUserId.value

    //     // }


    // })
    getemailvisible1.value = false
    formData.value = {}
    commentImage.value = null;
    formData.value.image = null;
    replyUserId.value = ""
    pCommentId.value = 0
    console.log(res);

    getcomment()


    // ElMessage({
    //     message:"未登录",
    //     type:"warning"
    // })
    // }


}


const getmulu = () => {
    nextTick(() => {
        const tocTags = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6'];
        const containDom = document.querySelector("#detail")
        const childNodes = containDom.childNodes;
        console.log(childNodes, "childNodes")
        let index = 0;
        childNodes.forEach(item => {
            let tagName = item.tagName;
            if (tagName == undefined || !tocTags.includes(tagName.toUpperCase())) {
                return true;
            }
            index++
            let id = "toc" + index;
            item.setAttribute("id", id);
            tocarray.value.push({
                id: id,
                title: item.innerText,
                level: Number.parseInt(tagName.substring(1)),
                offsetTop: item.offsetTop
            })
        })
        console.log(tocarray.value, "tocarray")
    })
}
const getcomment = async () => {
    const res = await service.get("/comment/loadcomment", {
        params: {
            articleId: route.params.boardId,
            pageNo: 1,
            orderType: 0
        }
    })
    console.log(res)
    commentlist.value = res.data
}
const getdetail = async () => {
    const res = await service.get("/forum/ArticleDetail", {
        params: {
            articleId: route.params.boardId
        }
    })
    console.log(res)
    haveLike.value=res.data.haveLike
    obj.value = res.data.forumArticleVo
    fjlist.value = res.data.forumArticleAttachmentVo
    getimage()
    highlightcode()
    getmulu()
    console.log(store.state.userInfo)
    userId.value = store.state.userInfo.userId;
}
const imageViewerRef = ref(null);
const closeViewer = () => {
    console.log("123")
    showViewer.value = null
    previewImgIndex.value = null
}
const highlightcode = () => {
    nextTick(() => {
        let blocks = document.querySelectorAll("pre code")
        blocks.forEach(item => {
            hljs.highlightBlock(item)
        })
    })
}
const getimage = () => {

    nextTick(() => {
        const list = document.querySelector("#detail").querySelectorAll("img");
        console.log(list)
        const imagelist = [];
        list.forEach((el, index) => {
            const src = el.getAttribute("src");
            console.log(src)
            imagelist.push(src);
            el.addEventListener("click", () => {
                console.log(ImageViewerref)
                showViewer.value = true;
                previewImgIndex.value = index
            })
        })
        previewImgList.value = imagelist;
    })

}
const download = async (item) => {
    console.log(item)
    window.location.href = "/api/forum/attachmentDownload?fileId=" + item.fileId
    // const res = await service.get("/forum/attachmentDownload", {
    //     params: {
    //         fileId: item.fileId
    //     }
    // })
    // console.log(res)
    // if (res.code == 0) {
    //     ElMessage({
    //         message: '未登录',
    //         type: 'warning',
    //         plain: true,
    //     })
    // } else {
    //     const elink = document.createElement('a');
    //     elink.download = item.fileName;
    //     elink.style.display = 'none';
    //     const blob = new Blob([res], { type: 'application/x-msdownload' });
    //     elink.href = URL.createObjectURL(blob);
    //     document.body.appendChild(elink);
    //     elink.click();
    //     document.body.removeChild(elink);
    // }
}
</script>
<style scoped>
.active{
    border-left: 1px solid blue !important;
}
  .tocitem:hover {
          background: #eeeded;
        }
.tocitem {
    cursor: pointer;
    text-decoration: none;
    display: block;
    line-height: 30px;
   
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: #555666;
    border-radius: 3px;
    font-size: 14px;
    border-left: 2px solid #fff;
}
.mulutitle {
    border-bottom: 1px solid #ddd;
    padding: 10px;
}

.mulu-contain {
    position: fixed;
    width: 285px;
    background: #fff;
}

.mulu {
    width: 285px;
    position: absolute;
    top: 45px;
    right: 0px;
    background: #fff;

}

.postcomment {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.detailglobal {
    width: 70%;
    padding: 10px;
    position: relative;
    box-sizing: border-box;
    margin: 0 auto;
}

.fjlist {
    margin-top: 10px;
    background: #fff;
    width: 1000px;
    padding: 10px;
    display: flex;
    box-sizing: border-box;
}

.content {
    margin-top: 10px;
    width: 1000px;
    padding: 10px;
    box-sizing: border-box;
    background: #fff;
}

.title {
    font-size: 16px;
    font-weight: 700;
}

.personal {
    width: 100%;
    display: flex;
    margin-top: 10px;
    border-bottom: 1px solid #eeee;
    padding-top: 10px;
    padding-bottom: 10px;
    box-sizing: border-box;
    align-items: center;
}

.comment {
    padding: 10px;
    box-sizing: border-box;
    background: #fff;
    width: 1000px;
    margin-top: 10px;
}

.titlecomment {
    font-size: 23px;
    font-weight: 500;
}

.commentylist {
    width: 100%;
    height: auto;

}
</style>